package com.xiyoufang.mycli.db;

import com.jfinal.plugin.activerecord.Db;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.Location;
import picocli.CommandLine;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 席有芳 on 2021/11/22.
 *
 * @author 席有芳
 */
@CommandLine.Command(name = "migrate", description = "数据库工具: 迁移")
public class Migrate extends Connected {
    /**
     * 记录migrate的表
     */
    @CommandLine.Option(names = {"-t", "--table"}, description = "记录migrate的表, 例如: migrate_schema", interactive = true, echo = true)
    private String table;
    /**
     * 脚本目录
     */
    @CommandLine.Option(names = {"-d", "--dir"}, description = "脚本目录, 例如: db/migrate", interactive = true, echo = true)
    private String location;

    @Override
    public Integer doCall() {
        table = defaultIfNull(table, "migrate.table");
        location = defaultIfNull(location, "migrate.location");
        Map<String, String> placeholders = new HashMap<>(System.getenv());
        env.forEach((key, value) -> placeholders.put(String.valueOf(key), String.valueOf(value)));
        Flyway flyway = Flyway.configure().dataSource(Db.use().getConfig().getDataSource()).table(table).locations(Location.FILESYSTEM_PREFIX + location).placeholders(placeholders).baselineOnMigrate(true).load();
        flyway.migrate();
        return 0;
    }
}
